package com.lee.bemorebetter.degin.principle;

import java.util.Comparator;
import java.util.DoubleSummaryStatistics;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ：liylw
 * @date ：Created in 2021/3/25 15:34
 */
public class Aggregator {
    public static RequestStat aggregate(List<RequestInfo> requestInfos,long durationInMillis){


        DoubleSummaryStatistics summary = requestInfos.stream().collect(Collectors.summarizingDouble(RequestInfo::getResponseTime));
        long tps = summary.getCount()/durationInMillis*1000;
        List<RequestInfo> sortedList = requestInfos.stream().sorted(Comparator.comparing(RequestInfo::getResponseTime)).collect(Collectors.toList());
        long count = summary.getCount();
        int idx999 = (int) (count*0.999);
        int idx99 = (int) (count*0.99);
        double p999RespTime = sortedList.get(idx999).getResponseTime();
        double p99RespTime = sortedList.get(idx99).getResponseTime();
        RequestStat requestStat = new RequestStat();
        requestStat.setCount(summary.getCount());
        requestStat.setMaxResponseTime(summary.getMax());
        requestStat.setMinResponseTime(summary.getMin());
        requestStat.setAvgResponseTime(summary.getAverage());
        requestStat.setP999ResponseTime(p999RespTime);
        requestStat.setP99ResponseTime(p99RespTime);
        requestStat.setTps(tps);
        return requestStat;
    }
}
